//创建用户集合
const mongoose = require('mongoose');
//导入bcrypt进行密码加密
const bcrypt = require('bcrypt');
//引入joi模块
const Joi = require('joi');

//创建用户集合规则
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 10,
    },
    email: {
        type: String,
        //unique保证数据库集合中，本条文档不重复出现
        //用于设置邮箱等限制唯一的信息
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    role: {
        //admin=超级管理员，normal=普通用户
        type: String,
        required: true
    },
    state: {
        type: Number,
        //0为启用状态，1为禁用状态
        default: 0
    }
});
const User = mongoose.model('User', userSchema);

async function createUser() {
    const salt = await bcrypt.genSalt(10);
    const pass = await bcrypt.hash('123456', salt);
    const user = await User.create({
        username: '吴树郁',
        email: '2264161040@qq.com',
        password: pass,
        role: 'admin',
        state: 0,
    });
    return console.log(user + '插入成功');
}
// createUser();

//验证用户信息
const validate = function(user) {
    //设置验证规则
    const schema = Joi.object({
        username: Joi.string().min(2).max(10).required().error(new Error('用户名验证失败')),
        email: Joi.string().email().required().error(new Error('电子邮箱验证失败')),
        password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required().error(new Error('密码格式错误')),
        //调用valid方法来限制合法值
        role: Joi.string().valid('normal', 'admin').required().error(new Error('角色信息验证失败')),
        state: Joi.number().valid(0, 1).required().error(new Error('状态信息验证失败'))
    });
    //实施验证
    return schema.validateAsync(user);
}


module.exports = {
    //ES6中若属性名和属性值相同，可省略属性值
    //相当于User:User
    User,
    validate
}